package com.luculent.util.extension.datamasking.ser;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.luculent.util.extension.datamasking.annotation.Sensitive;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

/**
 * 字符串集合序列化
 * @author zhangyang
 * @date 2020/11/2 16:10
 */
public class CollectionSensitiveSerializer extends BaseSensitiveSerializer<Collection<String>> {


    public CollectionSensitiveSerializer(Sensitive sensitiveInfo) {
        super(sensitiveInfo.type(), sensitiveInfo.keepChars());
    }

    /**
     * 执行序列化方法
     *
     * @param value
     * @param gen
     * @param serializers
     * @throws IOException
     */
    @Override
    public void serialize(Collection<String> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        final int len = value.size();
        gen.writeStartArray(len);
        serializeContents(value, gen, serializers);
        gen.writeEndArray();
    }


    private void serializeContents(Collection<String> value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.setCurrentValue(value);
        Iterator<String> it = value.iterator();
        if (!it.hasNext()) {
            return;
        }
        while (it.hasNext()) {
            String elem = it.next();
            if (elem == null) {
                provider.defaultSerializeNull(gen);
            } else {
                stringSerialize(elem, gen);
            }
        }
    }


}
